<template>
  <div class="app-container">
    <div v-if="currentType === 'list'" v-loading="state.loading">
      <el-form v-show="state.showSearch" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="计划组名称" prop="searchTerm">
          <el-input v-model="queryParams.searchTerm" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="投放开始时间" prop="planTime">
          <el-date-picker
            style="width: 360px"
            v-model="queryParams.planTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
        </el-form-item>
        <el-form-item label="计划状态" prop="status">
          <el-select v-model="queryParams.status" clearable class="m-2" placeholder="请选择">
            <el-option
              v-for="item in searchStatusOptions"
              :key="item"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="城市标签" prop="cityName">
          <el-select
            v-model="queryParams.cityName"
            @change="handleSearch(true)"
            fit-input-width
            placeholder="请选择"
          >
            <el-option
              v-for="item in cityNameOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="&nbsp;">
          <el-button @click="handleSearch(false)">重置</el-button>
          <el-button type="primary" @click="handleSearch(true)">查询</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['devote:planGroup:add']"
            type="primary"
            icon="Plus"
            @click="handleAdd"
            >新增投放计划组</el-button
          >
        </el-col>
        <right-toolbar v-model:showSearch="state.showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <div class="plan-box">
        <el-card class="card-box" v-for="(item, index) in tableList" :key="index">
          <template #header>
            <div class="card-header">
              <span
                ><span style="font-size: 14px">计划组名称：</span
                ><label>{{ item.planName }}</label></span
              >
              <el-dropdown size="small" @command="handleAction($event, item)">
                <span class="el-dropdown-link">
                  操作
                  <el-icon class="el-icon--right">
                    <arrow-down />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit"
                      ><span v-hasPermi="['devote:planGroup:edit']">编辑</span></el-dropdown-item
                    >
                    <el-dropdown-item command="delete"
                      ><span v-hasPermi="['devote:planGroup:delete']">删除</span></el-dropdown-item
                    >
                    <!-- <el-dropdown-item command="print">打印</el-dropdown-item> -->
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          <div class="item-box" @click="handleDetails(item)" v-hasPermi="['devote:planGroup:info']">
            <div class="item"
              >投放时间：{{ formatDate1(item.startTime) + ' 至 ' + formatDate1(item.endTime) }}</div
            >
            <div class="item"
              >投放状态：<label :style="{ color: getStatusColor(item.status) }"
                >• 投放计划 {{ getStatusText(item.status) }}</label
              ></div
            >
          </div>
          <template #footer></template>
        </el-card>
        <el-card class="card-box no-content"> 活动建设中，敬请期待... </el-card>
      </div>
    </div>

    <groupinfo
      v-if="currentType === 'operate'"
      :receiveData="state"
      :devoteStatusOptions="devoteStatusOptions"
      @goback="goback"
      @cancel="cancel"
    />

    <detailinfo
      v-if="currentType === 'details'"
      :receiveData="state"
      :devoteStatusOptions="devoteStatusOptions"
      @goback="goback"
      @cancel="cancel"
    />
  </div>
</template>

<script setup name="devote">
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate1 } from '@/utils/index'
import { getDevoteList, deleteDevote } from '@/api/devote'
import { reactive } from 'vue'
import groupinfo from './groupinfo.vue'
import detailinfo from './details.vue'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => {
  queryParams.value.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  return globalStore.myCityList
})

const queryRef = ref(null)
const { proxy } = getCurrentInstance()

const currentType = ref('list')
const searchStatusOptions = ref([
  { name: '待投放', value: 'AwaitStart' },
  { name: '进行中', value: 'Ongoing' },
  { name: '已结束', value: 'End' }
])
const devoteStatusOptions = ref([
  { name: '待投放', value: 'AwaitStart' },
  { name: '进行中', value: 'Ongoing' },
  { name: '已失效', value: 'Invalidated' },
  { name: '已结束', value: 'End' }
])
const state = reactive({
  showSearch: true,
  data: {},
  loading: false,
  operType: '',
  cityName: ''
})
const queryParams = ref({
  page_index: 1,
  page_size: 1000,
  searchTerm: null,
  planTime: null,
  startTime: null,
  endTime: null,
  status: null,
  cityName: null
})
const tableList = ref([])

function handleSearch(confirm) {
  !confirm && queryRef.value.resetFields()
  getList(true)
}

async function getList(refresh) {
  state.loading = true
  if (refresh) queryParams.value.page_index = 1

  let { planTime = [], ...obj } = queryParams.value
  if (planTime && planTime.length) {
    obj.startTime = planTime[0] || ''
    obj.endTime = planTime[1] || ''
  }

  try {
    const res = await getDevoteList(obj)
    tableList.value = res?.data || []
    state.total = res?.data?.length || 0
  } finally {
    state.loading = false
  }
}

function cancel() {
  currentType.value = 'list'
}
function goback() {
  currentType.value = 'list'
  getList()
}

/**table Action */
function handleAdd() {
  currentType.value = 'operate'
  state.operType = 'add'
  state.cityName = queryParams.value.cityName
  state.data = {}
}
function handleAction(command, row) {
  if (command === 'edit') {
    currentType.value = 'operate'
    state.data = row
    state.operType = 'edit'
  } else if (command === 'delete') {
    ElMessageBox.confirm('确认删除' + '"' + row.planName + '"' + '吗?', '系统提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      center: false
    })
      .then(() => {
        deleteDevote({ planId: row.planId }).then(() => {
          getList()
          ElMessage.success('删除成功')
        })
      })
      .catch(() => {})
  } else {
    console.log('打印')
  }
}
function handleDetails(row) {
  currentType.value = 'details'
  state.cityName = queryParams.value.cityName
  state.data = row
  state.operType = 'view'
}

function getStatusText(status) {
  const match = devoteStatusOptions.value.find((option) => option.value === status)
  return match ? match.name : '未知'
}
function getStatusColor(status) {
  if (getStatusText(status) == '待投放') {
    return '#409eff'
  } else if (getStatusText(status) == '进行中') {
    return '#67c23a'
  } else {
    return '#f0864d'
  }
}
function getTimestamp(dateStr) {
  return new Date(dateStr).getTime()
}

/**init */
function init() {
  queryParams.value.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  getList()
}

init()
</script>

<style lang="scss" scoped>
.plan-box {
  width: 100%;
  height: auto;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: minmax(100px, auto);
  .card-box {
    margin: 16px 16px 0px 0px;
    cursor: pointer;
    :deep(.el-card__header) {
      padding: 14px 5px 7px !important;
    }
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .el-dropdown-link {
        cursor: pointer;
        color: var(--el-color-primary);
        display: flex;
        align-items: center;
      }
    }

    .item-box {
      .item {
        line-height: 30px;
        font-size: 14px;
      }
    }
  }
  .no-content {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    min-height: 150px;
  }
}
</style>
